<template>
  <PageContainer>
    <Header :title="adminData ? '管理员设置' : '添加管理员'" :data="adminData" />
    <view>
      <view v-if="!adminData" class="hb-bg-[#FFF4E7] hb-flex hb-items-center hb-py-3 hb-px-4">
        <TmIcon name="ali-icon icon-tips" color="#E29942" :font-size="32" />
        <TmText
          _class="hb-ml-2"
          label="手机号将作为识别管理员身份的关键信息，注意正确填写管理员手机号！"
          :line-height="44"
          color="#E29942"
          :font-size="28"
        />
      </view>
      <TmForm
        layout="vertical"
        :padding="[0, 0]"
        @submit="handleSubmit"
        :transparent="true"
        :border="false"
        v-model="formData"
      >
        <view class="hb-bg-white hb-pt-3 hb-pb-1 hb-px-4 hb-box-shadow-base hb-rounded-xl hb-mb-4">
          <TmFormItem
            label="管理员头像"
            :show-top-error-gap="false"
            required
            :margin="[0, 0]"
            :padding="[0, 0]"
            :transparent="true"
            :rules="[{ required: true, message: '请上传管理员头像' }]"
            field="avatar"
          >
            <ImgUpload
              v-model.number="uploadAvatar"
              :is-crop="true"
              :crop-options="{ width: 400, height: 400 }"
            />
          </TmFormItem>
        </view>
        <view class="hb-bg-white hb-pt-3 hb-pb-1 hb-px-4 hb-box-shadow-base hb-rounded-xl hb-mb-4">
          <TmFormItem
            label="管理员名称"
            :show-top-error-gap="false"
            required
            :margin="[0, 0]"
            :padding="[0, 0]"
            :transparent="true"
            :rules="[{ required: true, message: '请输入管理员名称' }]"
            field="userName"
          >
            <TmInput
              v-model="formData.userName"
              :font-size="28"
              show-char-number
              :maxlength="20"
              placeholder="请输入管理员名称"
            />
          </TmFormItem>
        </view>
        <view class="hb-bg-white hb-pt-3 hb-pb-1 hb-px-4 hb-box-shadow-base hb-rounded-xl hb-mb-4">
          <TmFormItem
            label="手机号"
            :show-top-error-gap="false"
            required
            :margin="[0, 0]"
            :padding="[0, 0]"
            :transparent="true"
            :rules="[
              { required: true, message: '请输入手机号' },
            { validator: (phone: string) => phoneReg.test(phone), message: '请输入正确的手机号码' }
            ]"
            field="phone"
          >
            <TmText
              v-if="adminData"
              _class="hb-mb-2"
              label="管理员手机号禁止修改，如需调整可删除或新增管理员"
              color="#969799"
              :font-size="24"
            />
            <TmInput
              v-model="formData.phone"
              :disabled="!!adminData"
              :font-size="28"
              placeholder="请输入手机号"
            />
          </TmFormItem>
        </view>

        <BottomSubmit
          :hide-cancel-btn="!(adminData && adminData?.roleType !== RoleTypeEnum.SUPER_ADMIN)"
          cancel-btn-label="删除管理员"
          :submit-btn-label="adminData ? '保存' : '确认添加'"
          :submit-loading="submitLoading"
          @cancel="modalVisible = true"
        />
      </TmForm>

      <TmModal
        v-model:show="modalVisible"
        title="删除管理员"
        :height="300"
        :follow-theme="false"
        cancel-text="取消"
        cancel-color="#969799"
        ok-color="#EA5E0E"
        ok-text="确认删除"
        @ok="handleDelete"
      >
        <view class="hb-text-sm hb-text-[#333] hb-text-center">
          <text>确定要删除管理员“</text>
          <text class="hb-text-primary">{{ adminData?.userName }}</text>
          <text>”吗？删除后，该用户将无法再协助你管理</text>
        </view>
      </TmModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* assistantSetting 管理员设置 */
  import { adminAddOrUpdate, botAdminDel } from '@/api/aiSettings';
  import { BotAdminPageListResult } from '@/api/aiSettings/types';
  import { RoleTypeEnum } from '@/enums/LoginEnum';
  import { AssistantSetting } from '@/router/types/modules';
  import { useUserStore } from '@/store/modules/user';
  import { Toast } from '@/utils';
  import { phoneReg } from '@/utils/Reg';

  const adminData = ref<BotAdminPageListResult>();
  let success: AssistantSetting['success'];

  const formData = reactive({
    userName: '',
    phone: '',
    avatar: '',
  });

  customOnload<'assistantSetting'>((op) => {
    adminData.value = op.data;
    formData.userName = adminData.value?.userName || '';
    formData.phone = adminData.value?.phone || '';
    formData.avatar = adminData.value?.avatar || '';
    success = op.success;
  });

  const uploadAvatar = computed({
    get() {
      return [formData.avatar];
    },
    set(value: string[]) {
      formData.avatar = value[0];
    },
  });

  const submitLoading = ref(false);
  /** 表单提交 */
  const handleSubmit = async (e: Tmui.tmFormSubmitResult<typeof formData>) => {
    if (!e.isPass) return;
    submitLoading.value = true;
    try {
      await adminAddOrUpdate({
        id: adminData.value?.id,
        userName: formData.userName,
        phone: formData.phone,
        avatar: formData.avatar,
      });
      success?.();
      Toast({
        title: '操作成功',
        success: () => {
          navigateBack();
        },
      });
    } finally {
      submitLoading.value = false;
    }
  };

  const modalVisible = ref(false);
  const handleDelete = async () => {
    await botAdminDel({ id: adminData.value?.id! });
    if (adminData.value?.phone === useUserStore().userInfo?.phone) {
      useUserStore().wxLogin();
      Toast({
        title: '管理员已移除',
        success: () => {
          reLaunch({
            name: 'aiSwitch',
          });
        },
      });
      return;
    }
    success?.();
    Toast({
      title: '管理员已移除',
      success: () => navigateBack(),
    });
  };
</script>

<style lang="scss" scoped></style>
